package com.eddie.community.controller.interceptor;

import com.eddie.community.annotion.LoginRequired;
import com.eddie.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Method;

/**
 * ClassName: LoginRequiredInterceptor
 * Package: com.eddie.community.controller.interceptor
 * Description:登录要求拦截器
 * Date: 2021/2/18 0018 22:03
 * Author: eddie_zhan@yeah.net
 */
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {
    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //排除静态资源
        if (handler instanceof HandlerMethod) {
            HandlerMethod handleMethod = (HandlerMethod) handler;
            Method method = handleMethod.getMethod();
            LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
            //需要登录 的方法，没有登录，返回到登录页面
            if (loginRequired != null && hostHolder.getUser() == null) {
                response.sendRedirect(request.getContextPath() + "/login");
                return false;
            }
        }
        return true;
    }
}
